const router = require('express').Router()
const stuDao = require('../dao/student')

router.get('/',(req, res) => {
  stuDao.query((err, data) => {
    if(err) return res.redirect('/500')
    res.render('index.html',{
      students: data
    })
  })
})

router.get('/new', (req, res) => {
  res.render('insert.html')
})

router.post('/new', (req, res) => {
  stuDao.add(req.body, err => {
    if(err) res.redirect('/500')
    res.redirect('/')
  })
})

router.get('/update', (req, res) => {
  stuDao.queryById(req.query.id, (err, data) => {
    if(err) res.redirect('/500')
    res.render('update.html',{
      student: data
    })
  })
})

router.post('/update', (req, res) => {
  stuDao.update(req.body, err => {
    if(err) res.redirect('/500')
    res.redirect('/')
  })
})

router.get('/delete', (req, res) => {
  stuDao.deleteStu(req.query.id, err => {
    if(err) res.redirect('/500')
    res.redirect('/')
  })
})

module.exports = router;
